package cn.dota2info.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 动态代理类
 * 可以用于扩展方法
 */
public class ProxySubject  implements MethodInterceptor {
    private Enhancer enhancer = new Enhancer();

    public Object getProxy(Class clazz) {
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(this);
        return enhancer.create();    //用于创建无参的目标对象代理类，对于有参构造器则调用Enhancer.create(Class[] argumentTypes, Object[] arguments)，第一个参数表示参数类型，第二个参数表示参数的值。
    }

    @Override
    public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("调用前");
        Test test=method.getAnnotation(Test.class);
        if(test!=null){
            System.out.println(test.name());
        }
        Object result = methodProxy.invokeSuper(object, args);
        System.out.println(method.getName());
        System.out.println("调用后");
        return result;
    }

    public static void main(String[] args) {
        RealSubject subject = (RealSubject) new ProxySubject().getProxy(RealSubject.class);
        subject.sayHello();
        subject.sayHi();
        System.out.println(subject.getClass().getName());
    }
}